import { System } from "@/FrontProcessing/System/System";
import { debounce } from "stl-typescript";
import { GyActor } from "@/FrontProcessing/Actors/GyActor";
import { devtool, IMouseEvent, OutLineActor } from "cax-base";
import { SelectedEdgeInfo } from "@/FrontProcessing";

export function removeFromSelectedEdgeSetByEdgeId(sys: System, id: string) {
  if (!sys.state.currentSelectedEdges.has(id)) return;
  sys.state.currentSelectedEdges.delete(id);
}

export function addToSelectedEdgeSetByEdgeId(
  sys: System,
  id: string,
  info: SelectedEdgeInfo
) {
  if (sys.state.currentSelectedEdges.has(id)) return;
  sys.state.currentSelectedEdges.set(id, info);
}

export function uniqueId(edgeId: number, faceId: number, partId: number) {
  return `${edgeId}_${faceId}_${partId}`;
}

export const func_edge_selector = debounce(
  (event: IMouseEvent, sys: System) => {
    const pos = event.position;
    const point = [pos.x, pos.y, 0.0];
    devtool.info(`🟢 当前选择点: ${point}`);
    sys.app.selector.vtPicker.pick(point, sys.app.renderer);
    if (sys.app.selector.vtPicker.getActors().length !== 0) {
      const modelPosition = sys.app.selector.vtPicker.getMapperPosition();
      const pickedCellId = sys.app.selector.vtPicker.getCellId();
      devtool.info(`🟢 当前选择index: ${pickedCellId}`);
      const back = sys.parent.selectorComp.getFaceIdByCellIndex(
        sys.app.actorList,
        pickedCellId,
        sys.state,
        sys.app.selector.getPickedVTActors() as GyActor[]
      );

      sys.app.actorList.value.forEach((actor: any) => {
        if (actor.isGyActor && actor.partId === back.partId) {
          const selectedEdgeIndexDict = (
            actor.outlines as OutLineActor
          ).coverEdgeColor(
            modelPosition,
            back.faceId,
            [55, 66, 250, 255],
            sys.state.currentSelectedEdgeStartIndex,
            sys.state.currentSelectedEdgeEndIndex,
            sys.state.currentSelectedEdgeOriginColor
          );
          const {
            selectedEdgeStartIndex,
            selectedEdgeEndIndex,
            selectedEdgeOriginColor,
            selectedEdgeId,
          } = selectedEdgeIndexDict;
          sys.state.currentSelectedEdgeStartIndex = selectedEdgeStartIndex;
          sys.state.currentSelectedEdgeEndIndex = selectedEdgeEndIndex;
          sys.state.currentSelectedEdgeOriginColor = selectedEdgeOriginColor;
        }
      });
      sys.app.window.render();
    }
  },
  50,
  false
);
